"""用户登录"""
import hashlib
import sm3
import sm2test
import sm4test
import func
import string
def decsalt():
    with open('salt.txt', 'rb') as ef:
        ecm  = ef.read()
    with open('sm4key.txt', 'rb') as f:
        key = f.read()
    plaintext=sm2test.sm2d(ecm)
    plaintext=plaintext.decode('utf-8')
    pllist=list(map(int, plaintext.split()))
    pl=func.list_to_bytes(pllist)
    print('为')
    print(plaintext)
    keytext=sm2test.sm2d(key)
    keytext=keytext.decode('utf-8')
    kylist = list(map(int, keytext.split()))
    ky = func.list_to_bytes(kylist)
    print('1为')
    print(keytext)
    plaintext_bytes = sm4test.SM4_ecb_dec(pl, ky)
    salt=plaintext_bytes.decode()
    return salt

def login():

    filename = 'users.txt'
    username = []
    active = 0

    import os  # 检测用户信息是否存在
    file_exist = os.path.exists(filename)
    if not file_exist:
        with open(filename, 'w'):
            print('暂无用户数据，请先注册！！！')
        quit()

    with open(filename, 'r') as file:
        names = file.read().splitlines()
        names = [name for name in names]
    while active == 0:
        usernameinput = input('请输入你的用户名：')
        userpasswordinput = input('请输入你的密码：')
        if (len(usernameinput.strip()) == 0) or (len(userpasswordinput.strip()) == 0):
            print('用户名或密码不为空,请重试！！！\n')
            continue
        for name_one in names:
            name_one = eval(name_one)
            username.append(name_one['username'])
        if usernameinput in username:
            for name_two in names:
                name_two = eval(name_two)
                if usernameinput == name_two['username']:
                    salt1=decsalt()
                    print('salt1为')
                    print(salt1)
                    pws = salt1 + userpasswordinput
                    after_hash_password = sm3.sm3_hash(func.bytes_to_list(pws))
                    if after_hash_password == name_two['password_hash']:
                        print('登录成功！！！')
                        active = 1
                        break
                    elif after_hash_password != name_two['password_hash']:
                        print('密码错误,请重试！！！\n')
                        break
        else:
            print('用户名不存在,请重试！！！\n')





